local conf = require("ufe.config")
local m = require("ufe.ufe_module")

local http_ufe_result = 'ufe_result'

local REASON_UFE_OFF = 0
local REASON_NOT_FOUND_APP = 1
local REASON_NOT_FOUND_ACF = 2
local REASON_NOT_FOUND_HOST = 3
local REASON_NOT_FOUND_URI = 4
local REASON_NOT_FOUND_UPS = 5
local REASON_NOT_MATCH = 6

local function exit_phase(reason)
    ngx.header[http_ufe_result] = 'A'..reason
    ngx.exit(ngx.OK)
end

function main()
    if ngx.var.ufe == 'off' then
		return exit_phase(REASON_UFE_OFF)
    end

	local app = ngx.var.app
	if not app or app == '' then
		return exit_phase(REASON_NOT_FOUND_APP)
	end

	-- get app config
	local acf = m.get_app_conf(app)
	if not acf then
		return exit_phase(REASON_NOT_FOUND_ACF)
	end

	local host = ngx.var.host

	if not host or host == '' then
		return exit_phase(REASON_NOT_FOUND_HOST)
	end

	local uri = ngx.var.uri
	if not uri then
		return exit_phase(REASON_NOT_FOUND_URI)
	end

	local ups = ngx.var.ups
	if not ups then
		return exit_phase(REASON_NOT_FOUND_UPS)
	end

	local group, key = m.get_group(acf, app, host, uri)
	if not group then
		return exit_phase(REASON_NOT_MATCH)
	end

	ngx.header[http_ufe_result] = 'B' .. key
	ups = group..'_'..ups

	ngx.var.ups = ups
end

local ok, err = pcall(main)
if not ok then
    ngx.log(ngx.ERR,"pcall(main) failed: ", tostring(err))
end
